/**
 * element ui beforeUpload
 * @param {Object} file
 * @returns Promise
 */
export function beforeImageUpload(file) {
    return new Promise((resolve, reject) => {
        const imageTypes = ['image/png', 'image/jpg', 'image/jpeg'];
        const isType = imageTypes.includes(file.type);
        const isLt4M = file.size / 1024 / 1024 < 4;

        if (!isType) {
            window.$message({type: 'error', message: '上传图片只能是 image/png,image/jpg,image/jpeg 格式!'});
            reject(new Error('上传图片只能是 image/png,image/jpg,image/jpeg 格式!'));
            return false;
        }
        if (!isLt4M) {
            window.$message({type: 'error', message: '上传图片大小不能超过4MB!'});
            reject(new Error('上传图片大小不能超过4MB!'));
            return isType && isLt4M;
        }

        // 60kb以内的无需压缩
        const isLimit60Kb = file.size / 1024 <= 60;

        if (isLimit60Kb) {
            resolve(file);
            return;
        }

        const image = new Image();
        let resultBlob = '';
        image.src = URL.createObjectURL(file);
        image.onload = () => {
            // 调用方法获取blob格式，方法写在下边
            resultBlob = compressUpload(image, file);
            resolve(resultBlob);
        };
        image.onerror = error => {
            reject(error);
        };
    });
}
/* 图片压缩方法-canvas压缩 */
export function compressUpload(image, file) {
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    // let initSize = image.src.length;
    const {width, height} = image;
    canvas.width = width;
    canvas.height = height;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(image, 0, 0, width, height);

    // 压缩率， 60Kb
    let ratio = Number((60 / (file.size / 1024)).toFixed(2));
    // console.log('ratio :>> ', ratio);
    ratio = ratio < 0.15 ? 0.15 : ratio;
    // 进行最小压缩0.1
    let compressData = canvas.toDataURL('image/jpeg', ratio);

    // 压缩后调用方法进行base64转Blob，方法写在下边
    let blobImg = dataURItoBlob(compressData);
    return blobImg;
}
/* base64转Blob对象 */
export function dataURItoBlob(data) {
    let byteString;
    if (data.split(',')[0].indexOf('base64') >= 0) {
        byteString = window.atob(data.split(',')[1]);
    } else {
        byteString = unescape(data.split(',')[1]);
    }
    let mimeString = data
        .split(',')[0]
        .split(':')[1]
        .split(';')[0];
    let ia = new Uint8Array(byteString.length);
    for (let i = 0; i < byteString.length; i += 1) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {type: mimeString});
}
